<?php
namespace app\common\service\WeChat;

use app\common\model\Merchant;

class Wechat
{
    public $app;
    public $config = [
//            'token'          => 'test',
//        'appid'          => 'wx75b5395047e5da56',
//        'appsecret'      => 'c44b18e44bdbb71fcf8e8dab0eeb6e55',
        'appid'          => 'wxe44635c633795dd2',
        'appsecret'      => '6eb54b5dc4ae258d7084ed921d41b8b8',
//            'encodingaeskey' => 'BJIUzE0gqlWy0GxfPp4J1oPTBmOrNDIGPNav1YFH5Z5',
            // 配置商户支付参数（可选，在使用支付功能时需要）
        'mch_id'         => "1524756001",
        'mch_key'        => '6eb54b5dc4ae258d7084ed921d41b8b8',
//            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
//            'ssl_key'        => '',
//            'ssl_cer'        => '',
//            // 缓存目录配置（可选，需拥有读写权限）
//            'cache_path'     => '',
    ];
    public function __construct()
    {
        include env('extend_path') . "WeChatDeveloper/include.php";
        $this->app = new \WeChat\Oauth($this->config);

    }
    public function oauth()
    {
        $url = $this->app->getOauthRedirect('http://mlwssc.top/index.php/mer/wxaccess');
        header('location:'.$url);
    }
    public function getAccessToken()
    {
        $access_token = $this->app->getOauthAccessToken();
        if(empty($access_token['openid'])) {
            exception('<h1>获取微信ID失败请返回重试</h1>') ;
        }
        Merchant::storeWxToken($access_token);
        header('location:http://mlwssc.top/mer/'); // 进入店主后台
    }
    public function payment()
    {
        $wechat = new \WeChat\Pay($this->config);
        $options = [
            'body'             => '测试商品',
            'out_trade_no'     => time(),
            'total_fee'        => '1',
            'openid'           => 'o38gpszoJoC9oJYz3UHHf6bEp0Lo',
            'trade_type'       => 'JSAPI',
            'notify_url'       => 'http://a.com/text.html',
            'spbill_create_ip' => '127.0.0.1',
        ];
        try {
            // 生成预支付码
            $result = $wechat->createOrder($options);
            // 创建JSAPI参数签名
            $options = $wechat->createParamsForJsApi($result['prepay_id']);
            // 把 $options 传到前端用js发起支付就可以了
            return [
                'code' => 1,
                'data' => $options
            ];
        } catch (\Exception $e) {
            return [
                'code' => 0,
                'msg' => $e->getMessage()
            ];
        }
    }
}